package cn.clx.org.service.impl;

import cn.clx.basic.service.impl.BaseServiceImpl;
import cn.clx.basic.util.MD5Utils;
import cn.clx.basic.util.StrUtils;
import cn.clx.org.domain.Employee;
import cn.clx.org.mapper.EmployeeMapper;
import cn.clx.org.query.DeptpartmentQuery;
import cn.clx.org.service.IEmployeeService;
import cn.clx.user.domain.Logininfo;
import cn.clx.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 用户新增级联新增logininfo表
     * @param employee
     */
    @Override
    public void save(Employee employee) {
        //设置盐值
        String salt = StrUtils.getComplexRandomString(16);
        employee.setSalt(salt);
        //设置密码加密
        String password = employee.getPassword();
        employee.setPassword(MD5Utils.encrypByMd5(password+salt));
        Logininfo logininfo=emp2logininfo(employee);
        employee.setLogininfo_id(logininfo.getId());
        super.save(employee);
    }
    //级联新增
    private Logininfo emp2logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0); //一定要设置
        logininfoMapper.save(logininfo);
        return logininfo;
    }

    /**
     * 员工修改级联修改logininfo表
     * @param employee
     */
    @Override
    public void update(Employee employee){
        Logininfo logininfo=emp2updateloginingfo(employee);
        employee.setLogininfo_id(logininfo.getId());
        super.update(employee);
    }
    //级联修改
    private Logininfo emp2updateloginingfo(Employee employee) {
        Logininfo logininfo = logininfoMapper.loadById(employee.getLogininfo_id());
        BeanUtils.copyProperties(employee,logininfo);
        logininfoMapper.update(logininfo);
        return logininfo;
    }


    @Override
    public void deleteArray(DeptpartmentQuery query) {
        //先把字符串转换成字符串数组  split 以，来分割  "1,23,53,2,65"  ==> [1,23,53,2,65]
        String[] strArr = query.getIds().split(",");
        //定义一个一样长度的Long数组
        Long[] ids = new Long[strArr.length];
        //通过循环转变成Long元素，在进行赋值到Long数组中
        for(int a=0;a<strArr.length;a++){
            ids[a] = Long.valueOf(strArr[a]);
        }
        employeeMapper.deleteArray(ids);
    }
}
